import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Layout, Dropdown, Menu, Space, Avatar } from "antd";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DownOutlined,
  UserOutlined,
} from "@ant-design/icons";

const { Header } = Layout;

export default function TopHeader() {
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  //拿到token里的用户名和角色名称
  const {
    role: { roleName },
    username,
  } = JSON.parse(localStorage.getItem("token"));
  const menu = (
    <Menu
      items={[
        {
          key: "1",
          label: roleName,
        },
        {
          key: "3",
          danger: true,
          label: "退出",
          onClick: function () {
            //清除token
            localStorage.removeItem("token");
            //重定向到登录页面
            navigate("/login");
          },
        },
      ]}
    />
  );
  return (
    <Header className="site-layout-background" style={{ padding: "0 16px" }}>
      {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
        className: "trigger",
        // 设置点击方向取反
        onClick: () => setCollapsed(!collapsed),
      })}
      <div style={{ float: "right" }}>
        <span>
          欢迎<span style={{ color: "#f0f" }}>{username}</span>回来
        </span>
        <Dropdown menu={menu}>
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              <Avatar size="large" icon={<UserOutlined />} />
              {/* <DownOutlined /> */}
            </Space>
          </a>
        </Dropdown>
      </div>
    </Header>
  );
}
